<template>
  <el-upload
    class="files-upload"
    :action="url"
    :accept="filesFormat"
    :multiple="isMultiple"
    :show-file-list="isShowList"
    :on-success="uploadSuccess"
    :on-error="uploadError"
  >
    <slot />
  </el-upload>
</template>

<script setup>
import { defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'

// 定义组件名称
defineOptions({
  name: 'Upload'
})

// 定义props
const props = defineProps({
  url: {
    type: String,
    default: ''
  },
  filesFormat: {
    type: String,
    default: ''
  },
  isMultiple: {
    type: Boolean,
    default: false
  },
  isShowList: {
    type: Boolean,
    default: false
  }
})

// 定义emits
const emit = defineEmits(['on-success', 'on-error'])

// 上传成功处理
const uploadSuccess = (res, file) => {
  if ([200, 0].includes(res.code)) {
    const data = res.data
    emit('on-success', data)
  } else {
    emit('on-error')
    ElMessage.error(res.msg)
  }
}

// 上传失败处理
const uploadError = (res, file) => {
  emit('on-error')
}
</script>

<style lang="less">
.files-upload{
  display: inline-block;
  vertical-align: top;
}
</style>
